from database import db
from datetime import datetime
import pytz

class Device(db.Model):
    __tablename__ = 'device'
    __table_args__ = {'extend_existing': True}

    id = db.Column(db.Integer, primary_key=True)
    device_id = db.Column(db.String(50), unique=True, nullable=False)
    name = db.Column(db.String(100), nullable=False)
    type = db.Column(db.String(50))
    location = db.Column(db.String(100))
    status = db.Column(db.String(20), default='offline')
    last_update = db.Column(db.DateTime, default=datetime.utcnow)

    def to_dict(self):
        return {
            'id': self.id,
            'device_id': self.device_id,
            'name': self.name,
            'type': self.type,
            'location': self.location,
            'status': self.status,
            'last_update': self.last_update.isoformat() if self.last_update else None
        }

class DeviceData(db.Model):
    __tablename__ = 'device_data'
    __table_args__ = {'extend_existing': True}
    __mapper_args__ = {'include_properties': ['id', 'device_id', 'operator', 'shift', 'average_speed', 'shift_length', 'timestamp']}

    id = db.Column(db.Integer, primary_key=True)
    device_id = db.Column(db.String(50), db.ForeignKey('device.device_id'), nullable=False)
    operator = db.Column(db.String(50))
    shift = db.Column(db.String(20))
    average_speed = db.Column(db.Float)
    shift_length = db.Column(db.Float)
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)

    def to_dict(self):
        return {
            'id': self.id,
            'device_id': self.device_id,
            'operator': self.operator,
            'shift': self.shift,
            'average_speed': self.average_speed,
            'shift_length': self.shift_length,
            'timestamp': self.timestamp.isoformat() if self.timestamp else None
        }
